﻿using WeDonekRpc.Helper;
using RpcStore.DAL;
using RpcStore.Model.DB;
using RpcStore.RemoteModel.Transmit.Model;

namespace RpcStore.Collect.lmpl
{
    internal class ServerTransmitCollect : IServerTransmitCollect
    {
        private readonly IServerTransmitConfigDAL _BasicDAL;

        public ServerTransmitCollect (IServerTransmitConfigDAL basicDAL)
        {
            this._BasicDAL = basicDAL;
        }
        public long[] CheckIsConfig (long schemeId, long[] serverId)
        {
            return this._BasicDAL.CheckIsConfig(schemeId, serverId);
        }
        public ServerTransmitConfigModel[] Gets (long schemeId, long[] serverId)
        {
            return this._BasicDAL.Gets(schemeId, serverId);
        }
        public ServerTransmitConfigModel[] Gets (long schemeId)
        {
            return this._BasicDAL.Gets(schemeId);
        }
        public ServerTransmitConfigModel Get (long schemeId, long serverId)
        {
            return this._BasicDAL.Get(schemeId, serverId);
        }
        public ServerTransmitConfigModel Get (long id)
        {
            return this._BasicDAL.Get(id);
        }
        public void Set (ServerTransmitConfigModel config, TransmitConfig[] configs)
        {
            if (config.TransmitConfig.IsEqual(configs))
            {
                return;
            }
            this._BasicDAL.Set(config.Id, configs);
        }

        public void Add (TransmitAdd add)
        {
            if (this._BasicDAL.CheckIsExists(add.SchemeId, add.ServerId))
            {
                throw new ErrorException("rpc.server.transmit.repeat");
            }
            add.TransmitConfig.ForEach(c =>
            {
                if (!c.Range.IsNull())
                {
                    c.Range.ForEach(a =>
                    {
                        if (a.BeginRange == a.EndRange && a.IsFixed == false)
                        {
                            a.IsFixed = true;
                        }
                    });
                    c.Range = c.Range.Distinct().ToArray();
                }
            });
            this._BasicDAL.Add(add);
        }

        public void Delete (ServerTransmitConfigModel config)
        {
            this._BasicDAL.Delete(config.Id);
        }
    }
}
